
#include "Random.hpp"
#include <vector>
#include <ctime>

bool Random::s_init = false;
int Random::s_seed = 0;

using namespace std;

Random::Random (DistType p_type, int p_seed) : m_type(p_type) 
{
  // initialize the random number generator
  if ( ! s_init )
    {
      if ( ! p_seed )
	s_seed = time(0);
      else
	s_seed = p_seed;
      // make sure the seed is negative
      if ( s_seed > 0 )
	s_seed *= -1;
      s_init = true;
    }
}

double
Random::CDF(double x)
{
  return x;
}
double
Random::InvCDF(double x)
{
  return x;
}

// NR ran1 function

double 
Random::rand()
{
  int& idum = s_seed;
  const int IA=16807,IM=2147483647,IQ=127773,IR=2836,NTAB=32;
  const int NDIV=(1+(IM-1)/NTAB);
  const double EPS=3.0e-16,AM=1.0/IM,RNMX=(1.0-EPS);
  static int iy=0;
  static vector<int> iv(NTAB);
  int j,k;
  double temp;

  if (idum <= 0 || !iy) {
    if (-idum < 1) idum=1;
    else idum = -idum;
    for (j=NTAB+7;j>=0;j--) {
      k=idum/IQ;
      idum=IA*(idum-k*IQ)-IR*k;
      if (idum < 0) idum += IM;
      if (j < NTAB) iv[j] = idum;
    }
    iy=iv[0];
  }
  k=idum/IQ;
  idum=IA*(idum-k*IQ)-IR*k;
  if (idum < 0) idum += IM;
  j=iy/NDIV;
  iy=iv[j];
  iv[j] = idum;
  if ((temp=AM*iy) > RNMX) return RNMX;
  else return temp;
}
